package com.yaosheng.thread.interview;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by yaosheng on 2021/7/6.
 */
public class ReentrantLockView {

    public static void main(String[] args) {

        char[] aI = "1234567".toCharArray ();
        char[] aC = "ABCDEFG".toCharArray ();

        Lock lock = new ReentrantLock ();
        Condition conditionT1 = lock.newCondition ();
        Condition conditionT2 = lock.newCondition ();

        new Thread ( () -> {
            try {
                lock.lock ();
                for(char c : aI){
                    System.out.println (c);
                    conditionT2.signal ();   //唤醒t2线程
                    conditionT1.await ();    //阻塞t1线程
                }
                conditionT2.signal ();
            } catch (InterruptedException e) {
                e.printStackTrace ();
            }finally {
                lock.unlock ();
            }
        },"t1").start ();

        new Thread ( () -> {
            try {
                lock.lock ();
                for(char c : aC){
                    System.out.println (c);
                    conditionT1.signal ();   //唤醒t1线程
                    conditionT2.await ();    //阻塞t2线程
                }
                conditionT1.signal ();
            } catch (InterruptedException e) {
                e.printStackTrace ();
            }finally {
                lock.unlock ();
            }
        },"t2").start ();
    }
}
